package middleware

import (
	"github.com/gin-gonic/gin"
	"liuche17.cn/go-blog/server/global"
	"liuche17.cn/go-blog/server/model/common/resp"
	"liuche17.cn/go-blog/server/tools"
	"strings"
)

var (
	AUTHORIZATION = "authorization"
	BEARER        = "Bearer"
)

// JWTAuth Jwt 校验中间件
func JWTAuth() gin.HandlerFunc {
	return func(c *gin.Context) {
		// 从头部得到 token
		bearToken := c.GetHeader(AUTHORIZATION)
		// token 校验
		if bearToken == "" || !strings.HasPrefix(bearToken, BEARER) {
			resp.NoAuth("未登录或非法访问", c)
			return
		}

		// 解析 token
		token := strings.Split(bearToken, " ")[1]
		// 保存用户信息至全局变量
		userInfo, err := tools.GetLoginUserInfo(token)
		if err != nil {
			resp.FailWithMessage(err.Error(), c)
		}
		global.GB_USER = userInfo
		// 权限校验 todo
		// 处理其他中间件
		c.Next()
	}
}
